package com.peach.stock.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.peach.stock.domain.StockModel;
import com.peach.stock.service.AnalysisService;

@RestController
@ResponseBody
public class WeiXinController {

	private static final Logger log = LoggerFactory.getLogger(WeiXinController.class);

	@Resource
    private AnalysisService analysisService;
	
	@RequestMapping(value="/test", method = RequestMethod.GET)
	public String test(String msg)
	{
		return process(msg);
	}
	
	@RequestMapping(value="/weixin", method = RequestMethod.GET)
	public String getWX(HttpServletRequest request, HttpServletResponse response)
	{
//		String signature = request.getParameter("signature");
//	    String timestamp = request.getParameter("timestamp");
//	    String nonce = request.getParameter("nonce");
//	    String echostr = request.getParameter("echostr");
//	    log.info(signature);
//	    log.info(timestamp);
//	    log.info(nonce);
//	    log.info(echostr);
	    
		return "v1.0.0";
	}
	
	@RequestMapping(value="/weixin", method = RequestMethod.POST)
	public String postWX(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String content = getContent(request.getInputStream());
		String openid = request.getParameter("openid");
		String crtTime = request.getParameter("timestamp");
		log.info(content);
//		log.info(openid);
//		log.info(crtTime);
		
		if (StringUtils.isEmpty(content) || content.trim().length() < 2)
		{
			return "error!!!";
		}
		
		return ceateText(openid, crtTime, process(content.trim()));
	}

	private String process(String msg)
	{
		String result = "命令格式错误!";
		if ("cd".equalsIgnoreCase(msg.substring(0, 2)))
		{// 超跌股
			String[] m = msg.split(" ");
			if (m.length == 2)
			{
				int s = Integer.parseInt(m[1]);
				if (s > 0 && s < 1000)
				{
					result = analysisService.getCD(s);
				}
			}
			else
			{
				result = analysisService.getCD(5);
			}
		}
		else
		{
			StockModel sm = analysisService.getStockModel(msg);
			if (sm != null)
			{
				result = sm.toString();
			}
		}
		return result;
	}
	
	/**
	 * 解析收到的消息
	 * @param is
	 * @return
	 */
	private String getContent(InputStream is) {
		try {
			SAXReader reader = new SAXReader();
			reader.setEncoding("UTF-8");
			Document document = reader.read(is);
			Element root = document.getRootElement();
			return (String) root.element("Content").getData();
		} catch (DocumentException e) {
			log.error(e.getMessage(), e);
		}
		return "";
	}

	/**
	 * 回复消息
	 * @param openid
	 * @param crtTime
	 * @param content
	 * @return
	 */
	private String ceateText(String openid, String crtTime, String content) {
		String msgTemp = "<xml><ToUserName><![CDATA[%s]]></ToUserName>"
				+ "<FromUserName><![CDATA[gh_a0d96cf99f21]]></FromUserName>" + "<CreateTime>%s</CreateTime>"
				+ "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>";

		return String.format(msgTemp, openid, crtTime, content);
	}
}
